package com.example.petadopt.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.petadopt.common.Result;
import com.example.petadopt.dao.UserDao;
import com.example.petadopt.entity.User;
import com.gzone.university.utils.AppUtils;

public class CurrentUserUtils {

    private static final String PREF_NAME = "user_pref";
    private static final String KEY_USER_ID = "current_user_id";

    /**
     * 获取当前登录用户信息
     *
     * @return 当前用户对象，如果未登录则返回null
     */
    public static User getCurrentUser() {
        SharedPreferences sharedPreferences = AppUtils.getApplication()
                .getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        long userId = sharedPreferences.getLong(KEY_USER_ID, -1);

        if (userId == -1) {
            throw new IllegalStateException("用户未登录");
        }

        Result<User> result = UserDao.getByUserId(userId);
        if (result.isSuccess()) {
            return result.getData();
        }

        throw new IllegalStateException("获取用户信息失败");
    }

    /**
     * 设置当前登录用户ID
     *
     * @param userId 用户ID
     */
    public static void setCurrentUser(long userId) {
        SharedPreferences sharedPreferences = AppUtils.getApplication()
                .getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putLong(KEY_USER_ID, userId);
        editor.apply();
    }

    /**
     * 清除当前登录用户信息（退出登录时使用）
     */
    public static void clearCurrentUser() {
        SharedPreferences sharedPreferences = AppUtils.getApplication()
                .getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(KEY_USER_ID);
        editor.apply();
    }
}